const { Ollama } = require("ollama");
const jwt = require("jsonwebtoken");
const express = require("express");
const mysql = require("mysql2/promise");
const router = express.Router();
const dbConfig = {
  host: "101.201.116.122",
  user: "kzqsh",
  password: "040829",
  database: "kzqsh",
};
const JWT_SECRET = "it-lxp ^-^";

const ollama = new Ollama({
  host: "http://127.0.0.1:11434",
});
// 注册接口
router.post("/register", async (req, res) => {
  const { account, password } = req.body;
  if (!account || !password) return res.json({ error: "账号和密码不能为空" });

  try {
    const conn = await mysql.createConnection(dbConfig);
    // 检查账号是否已存在
    const [rows] = await conn.execute("SELECT * FROM users WHERE account = ?", [
      account,
    ]);
    if (rows.length > 0) {
      await conn.end();
      return res.json({ error: "账号已存在" });
    }
    // 新建用户
    await conn.execute(
      "INSERT INTO users (account, password, nickname) VALUES (?, ?, ?)",
      [account, password, account]
    );
    const [userRows] = await conn.execute(
      "SELECT * FROM users WHERE account = ?",
      [account]
    );
    const user = userRows[0];
    await conn.end();

    // 生成token
    const token = jwt.sign({ id: user.id, account: user.account }, JWT_SECRET, {
      expiresIn: "7d",
    });
    res.json({
      token,
      userInfo: {
        id: user.id,
        account: user.account,
        nickname: user.nickname,
        avatarUrl: user.avatarUrl,
      },
    });
  } catch (err) {
    console.error(err);
    res.json({ error: "服务器错误", detail: err.message });
  }
});
// 退出登录接口
router.post("/logout", async (req, res) => {
  const { userId } = req.body;
  console.log("接收到的参数:", { userId });

  if (!userId) return res.json({ error: "用户ID不能为空" });

  try {
    const conn = await mysql.createConnection(dbConfig);
    await conn.execute("UPDATE users SET is_login =? WHERE id =?", [
      "false",
      userId,
    ]);
    await conn.end();
    res.json({ success: true, message: "退出登录成功" });
  } catch (err) {
    console.error(err);
    res.json({ error: "服务器错误", detail: err.message });
  }
})

// 登录接口
router.post("/login", async (req, res) => {
  const { account, password } = req.body;
  console.log("接收到的参数:", { account, password });

  if (!account || !password) return res.json({ error: "账号和密码不能为空" });

  try {
    const conn = await mysql.createConnection(dbConfig);
    const [rows] = await conn.execute("SELECT * FROM users WHERE account = ?", [
      account,
    ]);
    await conn.end();
    console.log("查询结果:", rows);

    if (rows.length === 0) return res.json({ error: "账号不存在" });
    const user = rows[0];

    if (user.password !== password) return res.json({ error: "密码错误" });
    if (user.is_login == "true") return res.json({ error: "账号已登录" });
    // 更新用户登录状态
    const conn2 = await mysql.createConnection(dbConfig);
    await conn2.execute("UPDATE users SET is_login = ? WHERE id = ?", [
      "true",
      user.id,
    ]);
    await conn2.end();
    // 生成token
    const token = jwt.sign({ id: user.id, account: user.account }, JWT_SECRET, {
      expiresIn: "7d",
    });
    res.json({
      token,
      userInfo: {
        userId: user.id,
        account: user.account,
        nickname: user.nickname,
        avatarUrl: user.avatarUrl,
      },
    });
  } catch (err) {
    console.error(err);
    res.json({ error: "服务器错误", detail: err.message });
  }
});
// 收藏相关
router.get("/favorites/list", async (req, res) => {
  const { userId } = req.query;
  console.log("接收到的参数:", { userId });

  const conn = await mysql.createConnection(dbConfig);
  const [rows] = await conn.execute(
    "SELECT * FROM favorites WHERE userId = ?",
    [userId]
  );
  await conn.end();
  res.json(rows);
});

router.post("/favorites/add", async (req, res) => {
  try {
    const { userId, title, content, tags } = req.body;

    // 参数验证和清理，确保没有undefined值
    const safeUserId = userId || null;
    const safeTitle = title || "";
    const safeContent = content || "";
    const safeTags = tags || "";

    console.log("接收到的参数:", { userId, title, content, tags });
    console.log("清理后的参数:", {
      safeUserId,
      safeTitle,
      safeContent,
      safeTags,
    });

    // 验证必要参数
    if (!safeUserId) {
      return res.status(400).json({
        success: false,
        error: "用户ID不能为空",
      });
    }

    const conn = await mysql.createConnection(dbConfig);

    // 使用清理后的参数执行SQL
    await conn.execute(
      "INSERT INTO favorites (userId, title, content, tags) VALUES (?, ?, ?, ?)",
      [safeUserId, safeTitle, safeContent, safeTags]
    );

    await conn.end();

    res.json({
      success: true,
      message: "收藏添加成功",
    });
  } catch (error) {
    console.error("添加收藏失败:", error);
    res.status(500).json({
      success: false,
      error: error.message,
    });
  }
});

router.post("/favorites/delete", async (req, res) => {
  const { userId, id } = req.body;
  const conn = await mysql.createConnection(dbConfig);
  await conn.execute("DELETE FROM favorites WHERE userId = ? AND id = ?", [
    userId,
    id,
  ]);
  await conn.end();
  res.json({ success: true });
});

// 健康提醒相关
router.get("/reminders/list", async (req, res) => {
  const { userId } = req.query;
  const conn = await mysql.createConnection(dbConfig);
  const [rows] = await conn.execute(
    "SELECT * FROM reminders WHERE userId = ?",
    [userId]
  );
  await conn.end();
  res.json(rows);
});

router.post("/reminders/add", async (req, res) => {
  const { userId, time, title, description, notified } = req.body;
  const conn = await mysql.createConnection(dbConfig);
  await conn.execute(
    "INSERT INTO reminders (userId, time, title, description, notified) VALUES (?, ?, ?, ?, ?)",
    [userId, time, title, description, notified ? 1 : 0]
  );
  await conn.end();
  res.json({ success: true });
});

router.post("/reminders/delete", async (req, res) => {
  const { userId, id } = req.body;
  const conn = await mysql.createConnection(dbConfig);
  await conn.execute("DELETE FROM reminders WHERE userId = ? AND id = ?", [
    userId,
    id,
  ]);
  await conn.end();
  res.json({ success: true });
});

router.get("/analysis/get", async (req, res) => {
  const { userId } = req.query;

  if (!userId) {
    return res.json({ success: false, error: "缺少用户ID" });
  }

  try {
    const conn = await mysql.createConnection(dbConfig);
    const [rows] = await conn.execute(
      "SELECT * FROM analysis_results WHERE userId = ? ORDER BY createTime DESC LIMIT 1",
      [userId]
    );
    await conn.end();

    if (rows.length > 0) {
      res.json({
        success: true,
        userId: rows[0].userId,
        healthData: rows[0].healthData,
        healthScore: rows[0].healthScore,
        aiAnalysis: rows[0].aiAnalysis,
        aiAdvice: rows[0].aiAdvice,
        createTime: rows[0].createTime,
      });
    } else {
      res.json({ success: false, message: "未找到分析结果" });
    }
  } catch (error) {
    console.error("获取分析结果失败:", error);
    res.json({ success: false, error: "数据库查询失败" });
  }
});

router.post("/analysis/save", async (req, res) => {
  const {
    userId,
    healthData,
    healthScore,
    aiAnalysis,
    aiAdvice,
    overwrite,
    timestamp,
  } = req.body;

  if (!userId) {
    return res.json({ success: false, error: "缺少用户ID" });
  }

  // 健壮性处理，防止为null
  const safeHealthData = healthData ? healthData : {};
  const safeAiAnalysis = aiAnalysis ? aiAnalysis : {};
  const safeAiAdvice = aiAdvice ? aiAdvice : [];

  try {
    const conn = await mysql.createConnection(dbConfig);

    // 首先检查是否已存在该用户的记录
    const [existingRows] = await conn.execute(
      "SELECT id FROM analysis_results WHERE userId = ?",
      [userId]
    );

    let result;
    if (existingRows.length > 0) {
      // 如果存在记录，则更新（覆盖）
      console.log("更新现有分析记录，用户ID:", userId);
      const [updateResult] = await conn.execute(
        `UPDATE analysis_results 
         SET healthData = ?, healthScore = ?, aiAnalysis = ?, aiAdvice = ?, createTime = NOW()
         WHERE userId = ?`,
        [
          JSON.stringify(safeHealthData),
          healthScore,
          JSON.stringify(safeAiAnalysis),
          JSON.stringify(safeAiAdvice),
          userId,
        ]
      );
      result = { success: true, overwritten: true, message: "分析结果已更新" };
    } else {
      // 如果不存在记录，则插入新记录
      console.log("创建新分析记录，用户ID:", userId);
      const [insertResult] = await conn.execute(
        "INSERT INTO analysis_results (userId, healthData, healthScore, aiAnalysis, aiAdvice) VALUES (?, ?, ?, ?, ?)",
        [
          userId,
          JSON.stringify(safeHealthData),
          healthScore,
          JSON.stringify(safeAiAnalysis),
          JSON.stringify(safeAiAdvice),
        ]
      );
      result = { success: true, overwritten: false, message: "分析结果已保存" };
    }

    await conn.end();
    res.json(result);
  } catch (error) {
    console.error("保存分析结果失败:", error);
    res.json({ success: false, error: "数据库保存失败" });
  }
});
// 可选：删除用户的分析结果
router.post("/analysis/delete", async (req, res) => {
  const { userId } = req.body;

  if (!userId) {
    return res.json({ success: false, error: "缺少用户ID" });
  }

  try {
    const conn = await mysql.createConnection(dbConfig);
    const [result] = await conn.execute(
      "DELETE FROM analysis_results WHERE userId = ?",
      [userId]
    );
    await conn.end();

    res.json({
      success: true,
      message: "分析结果已删除",
      deletedRows: result.affectedRows,
    });
  } catch (error) {
    console.error("删除分析结果失败:", error);
    res.json({ success: false, error: "数据库删除失败" });
  }
});

router.post("/chat", async (req, res) => {
  const { message } = req.body;
  console.log("Received message:", message);
  try {
    const response = await ollama.chat({
      model: "qwen3:8b",
      messages: [{ role: "user", content: message }],
    });
    console.log(response.message.content);

    res.send({
      status: 0,
      content: response.message.content,
    });
  } catch (error) {
    console.error("Error:", error);
    res.send({ status: 1, content: error.message });
  }
});
module.exports = router;
